package org.faster.dal.criteria;

import java.io.Serializable;
import java.util.LinkedHashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.faster.dal.utils.JsonUtils;

public class Model implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = 3485804608796833321L;
    
    private final LinkedHashMap<String, Object> content;
    
    public static final String MODEL_NAME = "table_name";
    
    public static final String MODEL_ID = "single_primary_key";
    
    public Model(String modelName){
        content = new LinkedHashMap<String, Object>();
        content.put(MODEL_NAME, modelName);
    }
    
    public Model(Class<?> clazz){
        content = new LinkedHashMap<String, Object>();
        String name = clazz.getName();
        name = name.substring(name.lastIndexOf(".")+1);
        char[] array = name.toCharArray();
        array[0] += 32;
        content.put(MODEL_NAME, String.valueOf(array));
    }
    
    public Model(Object obj){
        content = new LinkedHashMap<String, Object>();
        String name = obj.getClass().getName();
        content.put(MODEL_NAME, firstToLower(name.substring(name.lastIndexOf(".")+1)));
        Map<String, Object> map = (Map<String, Object>) JsonUtils.objToMap(obj);
        content.putAll(map);
    }
    
    public Model(String modelName, Map<String, Object> obj){
        content = new LinkedHashMap<String, Object>();
        content.put(MODEL_NAME, modelName);
        content.putAll(obj);
    }
    
    public void setSinglePrimaryKey(Object primaryKey){
        content.put(MODEL_ID, primaryKey);
    }
    
    public String getTableName(){
        return (String) content.get(MODEL_NAME);
    }
    
    public void setField(String field, Object value){
        if(StringUtils.isEmpty(field)){
            return;
        }
        content.put(field, value);
    }
    
    public Object getField(String field){
        if(StringUtils.isEmpty(field)){
            return null;
        }
        return content.get(field);
    }
    
    public  LinkedHashMap<String, Object> getContent(){
        return content;
    }
    
    public void addContent(Map<String, Object> content){
        this.content.putAll(content);
    }
    
    public int hashCode(){
        final int prime = 31;
        int result = 2;
        result = prime * result + content.hashCode();
        return result;
    }
    
    private String firstToLower(String str){
        char[] array = str.toCharArray();
        array[0] += 32;
        return String.valueOf(array);
    }

}
